<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">

      <span style="margin-left:10px">政策标题：</span>
      <el-input v-model="listQuery.title" @keyup.enter.native="handleFilter" class="filter-item widht" placeholder="请输入关键字" clearable>
      </el-input>
      
      <span style="margin-left:10px">发布作者：</span>
      <el-input v-model="listQuery.authorName" class="widht" placeholder="请输入资讯作者" clearable></el-input>
      
      <span style="margin-left:10px">热门推荐：</span>
      <el-select v-model="listQuery.recommend" placeholder="请选择" style="width: 120px;" clearable>
        <el-option label="是" :value='1'></el-option> 
        <el-option label="否" :value='0'></el-option>
      </el-select>      
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row :default-sort="{prop: 'createTime', order: 'descending'}" @selection-change="handleSelectionChange" @sort-change="getSortList" style="width: 100%">

      <el-table-column align="center" label="ID" min-width="50">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="110" align="center" label="政策标题" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="110" align="center" label="发布作者" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.authorName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="权重值" min-width="80" sortable="custom" prop="weight"></el-table-column>

      <el-table-column align="center" label="阅读数" min-width="80" sortable="custom" prop="viewCount"></el-table-column>

      <el-table-column align="center" label="点赞数" min-width="80" sortable="custom" prop="likeCount"></el-table-column>

      <el-table-column align="center" label="热门推荐" min-width="80">
        <template slot-scope="scope">
        <span>{{scope.row.recommend == 1 ? "是" : "否"}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="120" align="center" label="发布日期" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | dateformat('YYYY-MM-DD HH:mm') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="handleModifyStatus(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 70%; margin-left:50px;'>
        <el-form-item label="政策标题：" prop="title">
          <el-input type="textarea" maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="是否为热门推荐：">
          <el-radio-group v-model="temp.recommend">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="政策内容：" prop="content">
          <Tinymce :height=150 ref="editor" v-model="temp.content" :value="temp.content" />
        </el-form-item>
        <el-form-item label="权重值：">
          <el-input-number v-model="temp.weight" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="浏览数：">
          <el-input-number v-model="temp.viewCount" :min="0" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="点赞数：">
          <el-input-number v-model="temp.likeCount" :min="0" :step="1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="success" @click="handleviewShowClick">预览</el-button>
        <el-button type="primary" @click="updateData" :loading="updateButtonStatus">确定</el-button>
      </div>
    </el-dialog>

    <div class="viewShow">
      <el-dialog :show-close="false" :visible.sync="viewShowDialog" >
        <div class="information-cont">
          <h3>{{ temp.title }}</h3>
          <div class="smallLine">
            <span class="time">{{ temp.modifyTime|dateformat('YYYY-MM-DD HH:mm') }}</span>
          </div>
          <div class="artical-cont" v-html="temp.content"></div>
        </div>    
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { queryResearchPolicyByPage, deleteResearchPolicyById, queryResearchPolicyById, updateResearchPolicyById } from '@/api/research'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import Multiselect from 'vue-multiselect' // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css' // 多选框组件css
export default {
  name: 'policyList',
  components: { Tinymce, Multiselect },
  data() {
    return {
      headers: {},
      inputVisible: false,
      inputValue: '',
      brandListOptions: [],
      dateformat: '',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        title: '',
        authorName: '',
        recommend: null,
        pageNo: 1,
        pageSize: 10
      },
      temp: {
          title:null,
          recommend:null,
          content:null,
          weight:null,
          viewCount:null,
          likeCount:null
      },
      dialogFormVisible: false,
      rules: {
        title: [{ required: true, message: '标题必填', trigger: 'blur' }],
        createTime: [{ type: 'date', required: true, message: '发布日期必填', trigger: 'change' }],
        viewCount: [{ required: true, message: '阅读数必填', trigger: 'blur' }]
      },
      updateButtonStatus : false,
      viewShowDialog: false,
      tableKey:''
    }
  },
  mounted() {
    this.getList()
    this.headers = { accessToken: getToken() }
  },
  methods: {
    // 查看预览
    handleviewShowClick() {
      this.viewShowDialog = true;
    },
    // 关闭
    handleClose() {
      this.$confirm('数据未保存，确认关闭？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogFormVisible = false
        }).catch(() => {});
    }, 
    getSortList(filed){
      let { prop, order } = filed
      let { listQuery } = this
      listQuery['sortField'] = prop
      if(prop){
        listQuery['sortWay'] = order == 'descending' ? 'DESC' : 'ASC'
      }else{
        listQuery['sortWay'] = null
      }
      this.listQuery = listQuery
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页查询
    getList() {
      this.listLoading = true;
      let params = this.listQuery;
      queryResearchPolicyByPage(params).then(response => {
        const { code, data: { total, list } } = response;
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      });
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    // 查询详情
    handleModifyStatus(row) {
      queryResearchPolicyById(row.id).then(response => {
        let { code, data } = response;
        data.createTime = new Date(data.createTime)
        this.temp = data
        this.dialogFormVisible = true
      })
    },
    // 编辑资讯
    updateData() {
      this.updateButtonStatus = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let { temp, temp:{ content, title} } = this;
          if(content.trim().length == 0 || content == '<p><br data-mce-bogus="1"></p>' || content  == '<p>&nbsp;</p>' || content == '<p><br></p>'){
              this.$message({
                message: '内容不能为空',
                type: 'error',
                duration: 1000
              });
              this.loading = false;
              this.updateButtonStatus = false;
              return;
          }               
          updateResearchPolicyById(temp).then(response => {
            let { code , message} = response
            if (code == 0) {
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }else{
              this.$message({
                title: '失败',
                message: message,
                type: 'error',
                duration: 2000
              })              
            }
          }).catch(err => {})
          .finally( ()=> {
            this.updateButtonStatus = false
          })
        }
      })
    },
    // 删除
    handleDelete(idx, row) {
      const { id } = row;
      this.$confirm('确定要进行删除操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteResearchPolicyById(id).then(response => {
          const { code } = response
          if (code == 0) {
            this.$notify({
              title: '成功',
              message: '删除研学资讯成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(idx)
            this.list.splice(idx, 1)
            this.total--
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: '删除研学资讯失败',
              type: 'error',
              duration: 2000
            })
          }
        });
      }).catch(() => {
      });
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

.viewShow {

  /deep/ .el-dialog {
    width: 350px;
    height: 760px;
    padding: 100px 12px;
    border-radius: 50px;
    background: url('../../assets/phone.png') no-repeat;
    background-size: 100% 100%; 

    .el-dialog__header {
      padding: 0;
    }

    .el-dialog__body {
      padding: 0;
      background: #fff;
      width: 100%;
      height: 100%;

      .information-cont{
        padding: 0 15px;
        background: #fff;
        white-space:normal; 
        word-break:break-all;
        height: 100%;
        overflow-y: auto;

        h3 {
          font-size: 20px;
          line-height: 32px;
          color: #333333;
          font-weight: bold;
          padding-top: 15px;
          margin: 0;

        }

        .smallLine{
          display: flex;
          display: -webkit-flex;
          justify-content:space-between;
          -webkit-justify-content: space-between;
          align-items: center;
          -webkit-align-items: center;
          font-size: 13px;
          color: #BBB;
          padding-top: 20px;
          padding-bottom: 17px;
          border-bottom: 1px solid #E5E8ED;
          .watch {
            padding: 0 0 0 20px;
            font-size: 17px;
            color: #C7C7C7;
          }
        }

        .artical-cont{
          padding-top: 16px;
          font-size: 15px;
          overflow: hidden;
          img{
            width: 100%;
          }
        }

      }

    }

  }

}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.widht{
  width: 180px;
}
.timeWidht{
  width: 300px;
}
</style>
